<?php
namespace App\ApiBackend\Department;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;


/**
 *  添加或编辑
 */
class AddUpdate extends ApiBaseController
{
  /**
   * 参数检查
   */
  protected function check(): void
  {
    // 定义规则
    $ruleArr = [
      'id' => 'required',
      'pid' => 'required',
      'deptName' => 'required',
      'orderNo' => 'required',
    ];
    $messageArr = [
      'required' => ':attribute必须填写',
    ];
    //验证
    $validator = Validator::make(request()->all(), $ruleArr, $messageArr, [
    ]);
    //验证失败
    if ($validator->stopOnFirstFailure()->fails()) {
      $this->result["code"] = 1;
      $this->result["message"] = $validator->errors()->first();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $isUpdate = $id = request('id');
    //数据
    $insertData = [
      "deptName" => request('deptName'),
      "pid" => request('pid'),
      "orderNo" => request('orderNo'),
    ];
    try {
      if ($isUpdate) {//更新
        DB::table('admin_department')->where('id', $id)->update($insertData);
      } else {//新增
        DB::table('admin_department')->insert($insertData);
      }
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
    return;
  }
}

